package com.blunka.framework.client.db.druid;


import java.io.File;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.Statement;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import com.alibaba.druid.sql.ast.SQLStatement;
import com.alibaba.druid.sql.dialect.mysql.parser.MySqlStatementParser;
import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlOutputVisitor;
import com.blunka.framework.client.constants.InitDesignConfig;
import com.blunka.framework.client.db.druid.service.ISQLService;
import com.blunka.framework.client.db.druid.service.MSSQLServer;
import com.blunka.framework.client.db.druid.service.MySqlServer;
import com.blunka.framework.client.db.druid.service.OracleServer;
import com.blunka.framework.client.db.druid.service.SqlLiteServer;
import com.blunka.framework.client.utils.DesignUtils;

/**
 *
 *
 * @平台：统一开发平台
 * @文件名称：DBHelper.java
 * @文件描述：
 * @author xuqiang
 * @日期：2018年5月25日下午2:38:43
 *
 */
public class DBSQLService {

	private static final Logger logger = Logger.getLogger(DBSQLService.class);

	/**
	 * 服务端数据库
	 */
	private static ISQLService service;

	/**
	 * 本地缓存数据库
	 */
	private static ISQLService localserviceDbHelper;
	
	/**
	 * 本地缓存数据库
	 */
	public static String LOCAL_DB_FILE = DesignUtils.getDir()+"/res/db/thumnp.db";

	static{
		try{
			logger.info("初始化系统。。。。。");
			String dbtype = InitDesignConfig.getDBType();
			switch(dbtype){
				case "MYSQL":{
					service = MySqlServer.newInstance();
					break;
				}
				case "ORACLE":{
					service = OracleServer.newInstance();
					break;
				}
				case "MSSQL":{
					service = MSSQLServer.newInstance();
					break;
				}
				default:{
					logger.error("系统启动失败，无效的数据库连接类型");
					System.exit(0);
				}
			}
			if(service == null){
				logger.error("初始化服务器数据库失败，请确保配置或者网络环境是否正常");
			}else{
				String dburl = LOCAL_DB_FILE;//DesignUtils.getDir()+"/res/db/thumnp.db";
				File dbfile = new File(dburl);
				if(!dbfile.exists()){
					dbfile.getParentFile().mkdirs();
					String url = "jdbc:sqlite:" + dburl;
					Connection conn = DriverManager.getConnection(url);
					if (conn != null) {
						DatabaseMetaData meta = conn.getMetaData();
						logger.info("创建本地缓存文件成功,"+meta.getDriverName());
						//创建本地缓存表
						conn.setAutoCommit(false);
						Statement stmt = conn.createStatement();
						List<String> localSqlList = InitDesignConfig.getLocalDBSql();
						for(String sql : localSqlList){
							stmt.addBatch(sql);
						}
						stmt.executeBatch();
						stmt.close();
						conn.commit();
						conn.close();
					}
				}
				localserviceDbHelper = SqlLiteServer.newInstance();
				logger.info("系统数据初始化成功");
			}
		}catch(Exception e){
			logger.error("获取数据库连接配置文件异常",e);
		}
	}

	/**
	 * 获取远程数据库服务
	 * @return
	 */
	public static ISQLService getDBService(){
		return service;
	}

	/**
	 * 获取本地缓存数据库服务
	 * @return
	 */
	public static ISQLService getLocalDBService(){
		return localserviceDbHelper;
	}

	/**
	 * 判断sql语句是否合法,可以支持校验sql语句，视图等
	 * @param sql
	 * @return
	 */
	public static boolean parseSql(String sql){
		try{
			if(StringUtils.isEmpty(sql)){
				return false;
			}
	        MySqlStatementParser parser = new MySqlStatementParser(sql);
	        List<SQLStatement> stmtList = parser.parseStatementList();

	        // 将AST通过visitor输出
	        StringBuilder out = new StringBuilder();
	        MySqlOutputVisitor visitor = new MySqlOutputVisitor(out);

	        for (SQLStatement stmt : stmtList) {
	            stmt.accept(visitor);
	            out.setLength(0);
	        }
	        return true;
		}catch(Exception e){
			logger.error("校验sql语句异常，sql语句不合法",e);
		}

		return false;
	}

}
